package com.oepm.web.controller;

import com.oepm.biz.MajorProAppBiz;
import com.oepm.common.entity.Meta;
import com.oepm.common.entity.Result;
import com.oepm.common.utils.JWTUtil;
import com.oepm.dao.entity.MajorProAppPo;
import com.oepm.dao.entity.QueryInfo;
import com.oepm.vo.DataVo;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;

@CrossOrigin
@RestController
public class MajorProAppController {
    @Autowired
    MajorProAppBiz majorProAppBiz;
    @Value(value = "${upload_path}")
    private String upload_path;//资源文件绝对地址目录
    /**
     * 生请表上传
     * @param file
     * @param pid
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping("/keyUpload/upload")
    @RequiresRoles(value = {"4"})
    public Result uploadApp(@RequestParam("file") MultipartFile file,
                            @RequestParam("pid") String pid,
                            HttpServletRequest request) throws IOException {
        //判断文件是否为空
        if (file.isEmpty()) {
            return new Result(Meta.FAIL);
        }
        System.out.println(pid);
        //上传路径保存设置
        //String path = request.getServletContext().getRealPath(upload_path+"/uploadApp/"+pid);
        File realPath = new File(upload_path+"/uploadApp/"+pid);
        if (!realPath.exists()){
            realPath.mkdirs();
        }
        //每次上传删除上次上传文件
        File[] files = realPath.listFiles();
        for (File file1:files){
            file1.delete();
        }
        //上传文件地址
        System.out.println("上传文件保存地址："+realPath);

        String filename = file.getOriginalFilename();
        //通过CommonsMultipartFile的方法直接写文件（注意这个时候）
        file.transferTo(new File(realPath +"/"+ filename));
        //保存到数据库
        String address = "/"+pid+"/"+filename;
        MajorProAppPo MajorProAppPo = new MajorProAppPo(pid,filename,address);
        int flag = majorProAppBiz.uploadApp(MajorProAppPo);
        if(flag==1){
            return new Result(Meta.SUCCESS);
        }
        return new Result(Meta.FAIL);
    }

    /**
     * 下载
     * @param response
     * @param pid
     * @return
     * @throws IOException
     */
    @RequestMapping("/keyVerify/download/{pid}")
    @RequiresRoles(logical = Logical.OR,value = {"1","2","3","4"})
    public Result downloadApp(HttpServletResponse response,
                              @PathVariable String pid) throws IOException {
        //要下载的图片地址
        MajorProAppPo app = majorProAppBiz.selectAppByPid(pid);
        if (app.getApp_name() == null | app.getApp_address().equals("")){
            return new Result(Meta.FAIL);
        }
        //1、设置response 响应头
        response.reset(); //设置页面不缓存,清空buffer
        response.setCharacterEncoding("UTF-8"); //字符编码
        response.setContentType("multipart/form-data"); //二进制传输数据

        //跨域设置
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
        response.addHeader("Access-Control-Allow-Headers", "*");


        //设置响应头
        response.setHeader("Content-Disposition",
                "attachment;fileName="+ URLEncoder.encode(app.getApp_name(), "UTF-8"));

        File file = new File(upload_path+"/uploadApp/"+app.getApp_address());

        System.out.println("文件下载地址："+upload_path+"/uploadApp/"+app.getApp_address());
        //2、 读取文件--输入流
        InputStream input=new FileInputStream(file);
        //3、 写出文件--输出流
        OutputStream out = response.getOutputStream();
        //创建缓冲区
        byte[] buff =new byte[1024];
        int index=0;
        //4、执行 写出操作
        while((index= input.read(buff))!= -1){
            out.write(buff, 0, index);
            out.flush();
        }
        out.close();
        input.close();
        return new Result(Meta.SUCCESS);
    }

    /**
     * 教师申请书列表
     * @param request
     * @return
     */
    @GetMapping("/keyUpload/select")
    @RequiresRoles(value = "4")
    public Result selectByTeaId(HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String id = JWTUtil.getUserId(token);
        List<MajorProAppPo> list = majorProAppBiz.selectByTeaId(id);
        Result result = new Result(Meta.SUCCESS, list);
        return result;
    }

    /**
     * 校区管理员院长列表
     * @param queryInfo
     * @return
     */
    @GetMapping("keyVerify/select")
    @RequiresRoles(logical = Logical.OR,value = {"1","3"})
    public Result selectAll(HttpServletRequest request,QueryInfo queryInfo){
        String token = request.getHeader("Authorization");
        String roleId = JWTUtil.getRoleId(token);
        System.out.println(roleId);
        DataVo dataVo = new DataVo();
        if(roleId.equals("1")){
            dataVo = majorProAppBiz.selectAll(queryInfo);
        }else if(roleId.equals("3")){
            String academy = JWTUtil.getAcademy(token);
            dataVo = majorProAppBiz.selectByAcademy(queryInfo,academy);
        }
        Result result = new Result(Meta.SUCCESS, dataVo);
        return result;
    }

    /**
     * 审核
     * @param app
     * @return
     */
    @PostMapping("/keyVerify/update")
    @RequiresRoles(logical = Logical.OR,value = {"1","3"})
    public Result updateApp(@RequestBody MajorProAppPo app){
        int flag = majorProAppBiz.updateApp(app);
        Result result;
        if (flag>0){
            result = new Result(Meta.SUCCESS);
        }else{
            result = new Result(Meta.FAIL);
        }
        return result;
    }
}
